﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using DTcms.Core.API.Filters;
using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Extensions;
using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;

namespace DTcms.Core.API.Controllers
{
    [Area("api")]
    [Route("api/[controller]")]
    [ApiController]
    public class AreaController : ControllerBase
    {
        private readonly IAreaService _areaService;
        private readonly IMapper _mapper;
        public AreaController(IAreaService areaService, IMapper mapper)
        {
            _areaService = areaService;
            _mapper = mapper;
        }

        /// <summary>
        /// 根据ID获取地区
        /// 示例：/api/area/1
        /// </summary>
        [HttpGet("{areaId}")]
        [Authorize]
        [AuthorizeFilter("Area", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] int areaId, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<AreasDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _areaService.QueryAsync<Areas>(x => x.Id == areaId);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{areaId}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var result = _mapper.Map<AreasDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 根据父节点获取一级列表
        /// 示例：/api/area/view/0
        /// </summary>
        [HttpGet("view/{parentId}")]
        [Authorize]
        [AuthorizeFilter("Area", ActionType.View)]
        public async Task<IActionResult> GetList([FromRoute] int parentId, [FromQuery] BaseParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy.IsNotNullOrEmpty()
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<AreasDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<AreasDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取数据库列表
            var resultFrom = await _areaService.QueryListAsync<Areas>(0,
                x => x.ParentId == parentId,
                searchParam.OrderBy.IsNotNullOrWhiteSpace() ? searchParam.OrderBy : "SortId,Id");
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<AreasDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取地区树目录列表
        /// 示例：/api/area/
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("Area", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<AreasDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //如果有查询关健字
            var parentId = 0; //父节点ID
            if (param.Keyword.IsNotNullOrWhiteSpace())
            {
                var model = await _areaService.QueryAsync<Areas>(x => x.Title.Contains(param.Keyword));
                if (model == null)
                {
                    return NotFound(ResponseMessage.Error("暂无查询记录"));
                }
                parentId = model.Id;
            }
            //获取数据库列表
            var resultFrom = await _areaService.QueryListAsync(parentId);
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var resultDto = resultFrom.ShapeData(param.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/api/area/
        /// </summary>
        [HttpPost]
        [Authorize]
        [AuthorizeFilter("Area", ActionType.Add)]
        public async Task<IActionResult> Add([FromBody] AreasEditDto modelDto)
        {
            //映射成实体
            var model = _mapper.Map<Areas>(modelDto);
            //写入数据库
            await _areaService.AddAsync(model);
            //映射成DTO再返回，否则出错
            var result = _mapper.Map<AreasDto>(model);
            return Ok(result);
        }

        /// <summary>
        /// 修改一条记录
        /// 示例：/api/area/1
        /// </summary>
        [HttpPut("{areaId}")]
        [Authorize]
        [AuthorizeFilter("Area", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] int areaId, [FromBody] AreasEditDto modelDto)
        {
            //查找记录
            var model = await _areaService.QueryAsync<Areas>(x => x.Id == areaId);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"地区{areaId}不存在或已删除"));
            }
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelDto, model);
            var result = await _areaService.SaveAsync();
            return NoContent();
        }

        /// <summary>
        /// 局部更新一条记录
        /// 示例：/api/area/1
        /// Body：[{"op":"replace","path":"/title","value":"new title"}]
        /// </summary>
        [HttpPatch("{areaId}")]
        [Authorize]
        [AuthorizeFilter("Area", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] int areaId, [FromBody] JsonPatchDocument<AreasEditDto> patchDocument)
        {
            var model = await _areaService.QueryAsync<Areas>(x => x.Id == areaId);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{areaId}不存在或已删除"));
            }

            var modelToPatch = _mapper.Map<AreasEditDto>(model);
            patchDocument.ApplyTo(modelToPatch, ModelState);
            //验证数据是否合法
            if (!TryValidateModel(modelToPatch))
            {
                return ValidationProblem(ModelState);
            }
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelToPatch, model);
            await _areaService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/api/area/1
        /// </summary>
        [HttpDelete("{areaId}")]
        [Authorize]
        [AuthorizeFilter("Area", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] int areaId)
        {
            if (!await _areaService.ExistsAsync<Areas>(x => x.Id == areaId))
            {
                return NotFound(ResponseMessage.Error($"数据{areaId}不存在或已删除"));
            }
            var result = await _areaService.DeleteAsync(x => x.Id == areaId);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/api/area?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("Area", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var areaIds = Ids.ToIEnumerable<int>();
            if (areaIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _areaService.DeleteAsync(x => areaIds.Contains(x.Id));

            return NoContent();
        }

        #region 前台调用接口============================
        /// <summary>
        /// 获取地区树目录列表
        /// 示例：/api/client/area
        /// </summary>
        [HttpGet("/api/client/area")]
        public async Task<IActionResult> ClientGetList([FromQuery] BaseParameter param)
        {
            return await GetList(param);
        }
        #endregion
    }
}
